package com.ltxtiyu.video.interceptor;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.ltxtiyu.video.common.*;
import com.ltxtiyu.video.entity.TokenStore;
import com.ltxtiyu.video.entity.User;
import com.ltxtiyu.video.service.app.UserService;
import com.ltxtiyu.video.tool.HttpTool;
import com.ltxtiyu.video.tool.Tool;
import org.apache.commons.lang3.StringUtils;
import org.hashids.Hashids;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

public class SecurityInterceptor implements HandlerInterceptor {
    public static final Logger _log = LoggerFactory.getLogger(SecurityInterceptor.class);
    @Reference
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();

//        session.setAttribute("userId","Yp5R9Ba0jLePKrwn7N");

        String requestUri = request.getRequestURI();
        String queryString = request.getQueryString();
        if (queryString != null && !queryString.equals("")) {
            requestUri += "?" + queryString;
        }
        session.setAttribute("originUrl", requestUri);
        String hashUserId = String.valueOf(session.getAttribute("userId"));
        if(session.getAttribute("userId") == null){
            if (isAjaxRequest(request)) {       // 用户未登录
                writeRes(response, RetEnum.H5_USER_NOT_LOGIN);
            } else {
                response.sendRedirect(request.getContextPath()
                        + "/login");
            }
            return false;
        }
        Integer userId = -1 ;
        try {
            Hashids hashids = new Hashids(ConfigConstant.HASH_IDS_SECRET_KEY, ConfigConstant.HASH_IDS_VALUE_LENGTH);
            userId = Integer.parseInt(String.valueOf(hashids.decode(hashUserId)[0]));
        }catch (Exception e){
            _log.error(">>>>>>>>>>>>>>hashids解析userId出错,userId: {}, 错误信息: {}" ,hashUserId, e);
        }

        User user = userService.selectByPrimaryKey(Integer.valueOf(userId));
        if(user == null){       // 用户不存在
            if (isAjaxRequest(request)) {
                writeRes(response, RetEnum.OAUTH_CHECK_INEXISTENCE);
            } else {
                response.sendRedirect(request.getContextPath()
                        + "/login");
            }
            return false;
        }
        if(user.getStatus() < 1){   // 用户被封停
            if (isAjaxRequest(request)) {
                writeRes(response, RetEnum.OAUTH_CHECK_BANNED);
            } else {
                response.sendRedirect(request.getContextPath()
                        + "/login");
            }
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }

    boolean isAjaxRequest(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null && "XMLHttpRequest"
                .equals(request.getHeader("X-Requested-With").toString()));
    }

    private void writeRes(HttpServletResponse response, RetEnum re)
            throws Exception {
        String json = JsonTool.genJson(re);
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(json);
        out.flush();
        out.close();
    }
}
